package com.cj.mobile.iabp.mvp.presenter;

import static com.cj.mobile.iabp.BuildConfig.IS_DEBUG_DATA;

import android.os.Bundle;
import android.text.TextUtils;

import com.cj.mobile.iabp.app.config.CommonRetryWithDelay;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.RxUtils;
import com.cj.mobile.iabp.mvp.contract.AddArchiveInfoContract;
import com.cj.mobile.iabp.mvp.model.entity.ArchiveInfo;
import com.cj.mobile.iabp.mvp.model.entity.DictInfo;
import com.cj.mobile.iabp.mvp.ui.adapter.PrimaryDiagnosisAdapter;
import com.cj.mobile.iabp.mvp.ui.adapter.SecondaryDiagnosisAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 2025/09/30 18:01
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class AddArchiveInfoPresenter extends BasePresenter<AddArchiveInfoContract.Model, AddArchiveInfoContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;

    // 患者id
    private String id;
    // 患者登记号
    private String code;
    // 患者姓名
    private String name;
    private String doctorId;
    private String deptId;
    // 当前模式是否为修改
    private boolean isModify;
    // 修改模式下的数据源
    private ArchiveInfo info;
    // 归档id
    private String archiveId;

    // 主要诊断数据源
    @Named("Primary")
    @Inject
    List<DictInfo> mPrimaryDiagnosis;
    @Named("PrimaryAdapter")
    @Inject
    PrimaryDiagnosisAdapter mPrimaryAdapter;

    // 次要诊断数据源
    @Named("Secondary")
    @Inject
    List<DictInfo> mSecondaryDiagnosis;
    @Named("SecondaryAdapter")
    @Inject
    SecondaryDiagnosisAdapter mSecondaryAdapter;

    @Inject
    public AddArchiveInfoPresenter(AddArchiveInfoContract.Model model, AddArchiveInfoContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mPrimaryAdapter = null;
        this.mPrimaryDiagnosis = null;
        this.mSecondaryAdapter = null;
        this.mSecondaryDiagnosis = null;
    }

    public void getBundleValues(Bundle bundle) {
        if (bundle != null) {
            id = bundle.getString("id");
            code = bundle.getString("code");
            name = bundle.getString("name");
            doctorId = bundle.getString("doctorId");
            deptId = bundle.getString("deptId");
            info = bundle.getParcelable("info");

            if (info != null) {
                archiveId = info.getId();
            }
        }

        isModify = info != null;
    }

    public void initData(Bundle bundle) {
        getBundleValues(bundle);
        // 显示登记号和患者姓名
        mRootView.showArchiveInfo(code, name, info);
        getDictList();
    }


    /**
     * 获取诊断
     */
    public void getDictList() {
        if (IS_DEBUG_DATA) {
            List<DictInfo> list = new ArrayList<>();
            list.add(new DictInfo(261, "诊断", 0, "1", "1", "冠心病", "1", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(263, "诊断", 0, "1", "3", "急性心梗", "2", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(265, "诊断", 0, "1", "5", "心脏瓣膜病", "3", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(262, "诊断", 0, "1", "2", "先心病", "4", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(264, "诊断", 0, "1", "4", "主动脉疾病", "5", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));

            mPrimaryDiagnosis.addAll(list);
            mSecondaryDiagnosis.addAll(list);

            mPrimaryAdapter.notifyDataSetChanged();
            mSecondaryAdapter.notifyDataSetChanged();
        } else {
            mModel.getDictList()
                    .compose(RxUtils.applySchedulers(mRootView))                                    // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<List<DictInfo>>(mErrorHandler) {

                        @Override
                        public void onNext(List<DictInfo> list) {
                            if (CommonUtils.isNotEmpty(list)) {
                                // 清空原有数据
                                mPrimaryDiagnosis.clear();
                                mSecondaryDiagnosis.clear();

                                // 深拷贝 list 中的数据到 mPrimaryDiagnosis 和 mSecondaryDiagnosis
                                for (DictInfo item : list) {
                                    mPrimaryDiagnosis.add(new DictInfo(item));  // 假设 DictInfo 有拷贝构造函数
                                    mSecondaryDiagnosis.add(new DictInfo(item)); // 假设 DictInfo 有拷贝构造函数
                                }

                                // 如果是修改模式，则重新赋值选中的数据
                                if (isModify) {
                                    // 主要诊断
                                    if (!TextUtils.isEmpty(info.getDiagMain())) {
                                        // 将item值选中
                                        for (DictInfo item : mPrimaryDiagnosis) {
                                            if (item.getValue().equals(info.getDiagMain())) {
                                                item.setCheckBox(true);
                                            }
                                        }
                                    }

                                    // 次要诊断
                                    if (!TextUtils.isEmpty(info.getDiagSec())) {
                                        // 数据拆分
                                        String[] split = info.getDiagSec().split(",");
                                        for (String item : split) {
                                            for (DictInfo item2 : mSecondaryDiagnosis) {
                                                if (item2.getValue().equals(item)) {
                                                    item2.setCheckBox(true);
                                                }
                                            }
                                        }

                                    }
                                }

                                mPrimaryAdapter.notifyDataSetChanged();
                                mSecondaryAdapter.notifyDataSetChanged();
                            } else {
                                mRootView.notDiagnosis();
                            }
                        }
                    });
        }
    }


    /**
     * 新增归档信息
     *
     * @param pre         暂存0或提交1
     * @param regCode     注册代码
     * @param status      归档状态
     * @param alive       患者状态
     * @param ga          肌钙蛋白
     * @param leftSize    左室舒张末期内径
     * @param leftScore   左室射血分数
     * @param diagContent 其它诊断
     * @param timeIcu     icu
     * @param timeMc      通气时间
     * @param runTime     住院时间
     */
    public void btnSubmit(String pre,
                          String regCode, String status, String alive,
                          String ga, String leftSize, String leftScore, String diagContent, String timeIcu,
                          String timeMc, String runTime) {
        if (IS_DEBUG_DATA) {
            mRootView.showMessage("信息维护成功！");
        } else {

            if (isModify) {
                // 修改归档信息
                mModel.updateArchive(pre, archiveId, id, doctorId, deptId,
                                regCode, name, status, alive,
                                ga, leftSize, leftScore, getPrimaryDiagnosis(), diagContent, timeIcu,
                                timeMc, runTime, getSecondaryDiagnosis())
                        .subscribeOn(Schedulers.io())
                        .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                        .doOnSubscribe(disposable -> {
                            mRootView.showLoadingSubmit();
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doFinally(() -> {
                            mRootView.hideLoadingSubmit();
                        }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                        .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                            @Override
                            public void onNext(Integer commonResponse) {
                                mRootView.showMessage("修改成功！");
                                mRootView.killMyself();
                            }
                        });

            } else {
                // 新增归档信息
                mModel.addArchive(pre, id, doctorId, deptId,
                                regCode, name, status, alive,
                                ga, leftSize, leftScore, getPrimaryDiagnosis(), diagContent, timeIcu,
                                timeMc, runTime, getSecondaryDiagnosis())
                        .subscribeOn(Schedulers.io())
                        .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                        .doOnSubscribe(disposable -> {
                            mRootView.showLoadingSubmit();
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doFinally(() -> {
                            mRootView.hideLoadingSubmit();
                        }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                        .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                            @Override
                            public void onNext(Integer commonResponse) {
                                mRootView.showMessage("保存成功！");
                                mRootView.killMyself();
                            }
                        });

            }
        }
    }


    /**
     * 获取选中的主要诊断
     */
    public String getPrimaryDiagnosis() {
        for (DictInfo info : mPrimaryAdapter.getInfos()) {
            if (info.isCheckBox()) {
//                return info.getCode();
                return info.getValue();
            }
        }

        return "";
    }

    /**
     * 获取选中的次要诊断
     */
    public String getSecondaryDiagnosis() {
        String result = "";
        for (DictInfo info : mSecondaryAdapter.getInfos()) {
            if (info.isCheckBox()) {
                if (TextUtils.isEmpty(result)) {
//                    result = info.getCode();
                    result = info.getValue();
                } else {
//                    result = result + "," + info.getCode();
                    result = result + "," + info.getValue();
                }
            }
        }

        return result;
    }
}